package czk.concrent.juc.semaphore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 能够同时进入的线程数
 *
 * @Author:ChenZhangKun
 * @Date: 2020/12/30 20:41
 */
public class SemaphorePractice {
    public static void main(String[] args) {
        // 设置能进入的最大线程数
        Semaphore semaphore = new Semaphore(5);
        for (int i = 0; i < 10; i++) {
            // 进来一个减1
            try {
                semaphore.acquire();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            new Thread(() -> {
                System.out.println(System.currentTimeMillis() + " 开始");
                try {
                    TimeUnit.SECONDS.sleep(1);
                    System.out.println(System.currentTimeMillis() + " 结束");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    // 释放后才会恢复
                    semaphore.release();
                }

            }).start();
        }
    }
}
